import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Checkbox, InputNumber, Empty, Input, Popconfirm } from 'antd';
import { DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { getCart, setCart, removeFromCart, updateCartQuantity } from '../../utils/storage';
import { isUserAuthenticated } from '../../utils/auth';
import { message } from '../../utils/message';
import { getProducts } from '../../utils/storage';
import './Cart.css';

const MobileCart = () => {
  const navigate = useNavigate();
  const [cartItems, setCartItems] = useState([]);
  const [filteredItems, setFilteredItems] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [isBatchMode, setIsBatchMode] = useState(false);

  useEffect(() => {
    loadCartData();
  }, []);

  useEffect(() => {
    filterCartItems();
  }, [cartItems, searchKeyword]);

  const loadCartData = () => {
    const cart = getCart();
    setCartItems(cart);
  };

  const filterCartItems = () => {
    if (!searchKeyword) {
      setFilteredItems(cartItems);
    } else {
      const filtered = cartItems.filter(item =>
        item.name.toLowerCase().includes(searchKeyword.toLowerCase())
      );
      setFilteredItems(filtered);
    }
  };

  const handleSearch = (value) => {
    setSearchKeyword(value);
  };

  const toggleBatchMode = () => {
    setIsBatchMode(!isBatchMode);
    if (!isBatchMode) {
      setSelectedItems([]);
    }
  };

  const handleBatchDelete = () => {
    if (selectedItems.length === 0) {
      message.warning('请选择要删除的商品');
      return;
    }
    
    selectedItems.forEach(cartId => {
      removeFromCart(cartId);
    });
    
    setSelectedItems([]);
    setIsBatchMode(false);
    loadCartData();
    message.success(`已删除 ${selectedItems.length} 件商品`);
  };

  const handleSelectItem = (cartId, checked) => {
    if (checked) {
      setSelectedItems([...selectedItems, cartId]);
    } else {
      setSelectedItems(selectedItems.filter(id => id !== cartId));
    }
  };

  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedItems(filteredItems.map(item => item.cartId));
    } else {
      setSelectedItems([]);
    }
  };

  const handleQuantityChange = (cartId, quantity) => {
    if (quantity <= 0) {
      handleRemoveItem(cartId);
      return;
    }
    
    // 获取当前商品项
    const item = cartItems.find(item => item.cartId === cartId);
    if (!item) return;
    
    // 获取最新的库存信息
    const products = getProducts();
    const product = products.find(p => p.id === item.id);
    
    if (product) {
      // 检查库存是否足够
      if (quantity > product.stock) {
        message.warning(`库存不足，当前库存为${product.stock}件`);
        // 设置为最大可用库存
        updateCartQuantity(cartId, product.stock);
        loadCartData();
        return;
      }
    }
    
    updateCartQuantity(cartId, quantity);
    loadCartData();
  };

  const handleRemoveItem = (cartId) => {
    removeFromCart(cartId);
    setSelectedItems(selectedItems.filter(id => id !== cartId));
    loadCartData();
    message.success('商品已移除');
  };

  const calculateTotal = () => {
    return cartItems
      .filter(item => selectedItems.includes(item.cartId))
      .reduce((total, item) => total + item.price * item.quantity, 0)
      .toFixed(2);
  };

  const handleCheckout = () => {
    if (!isUserAuthenticated()) {
      navigate('/app/login', { state: { from: { pathname: '/app/cart' } } });
      return;
    }

    if (selectedItems.length === 0) {
      message.warning('请选择要结算的商品');
      return;
    }

    const selectedProducts = cartItems.filter(item => selectedItems.includes(item.cartId));
    navigate('/app/order/confirm', { state: { products: selectedProducts } });
  };

  if (cartItems.length === 0) {
    return (
      <div style={{ padding: '40px 16px', textAlign: 'center' }}>
        <Empty 
          description="购物车空空如也"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
        <Button 
          type="primary" 
          onClick={() => navigate('/app')}
          style={{ marginTop: '16px' }}
        >
          去逛逛
        </Button>
      </div>
    );
  }

  return (
    <div className="cart-page">
      {/* 购物车头部 */}
      <div className="cart-header">
        <div className="cart-title">购物车</div>
        <div className="cart-search">
          <Input
            placeholder="搜索商品"
            prefix={<SearchOutlined />}
            value={searchKeyword}
            onChange={(e) => handleSearch(e.target.value)}
            allowClear
          />
        </div>
        <Button
          type={isBatchMode ? 'primary' : 'default'}
          size="small"
          onClick={toggleBatchMode}
          style={{
            height: '30px'
          }}
        >
          {isBatchMode ? '取消' : '批量管理'}

        </Button>
      </div>

      {/* 批量删除按钮 */}
      {isBatchMode && (
        <div className="batch-actions">
          <Popconfirm
            title={`确定要删除选中的 ${selectedItems.length} 件商品吗？`}
            onConfirm={handleBatchDelete}
            okText="确定"
            okButtonProps={{
              style: {
                height: '22px'
              }
            }}
            cancelText="取消"
          >
            <Button 
              danger 
              disabled={selectedItems.length === 0}
              icon={<DeleteOutlined />}
            >
              批量删除 ({selectedItems.length})
            </Button>
          </Popconfirm>
        </div>
      )}

      {/* 购物车商品列表 */}
      <div className="cart-content">
        {filteredItems.map(item => (
        <div key={item.cartId} className="cart-item">
          <Checkbox
            checked={selectedItems.includes(item.cartId)}
            onChange={(e) => handleSelectItem(item.cartId, e.target.checked)}
          />
          
          <img 
            src={item.images[0]} 
            alt={item.name}
            className="cart-item-image"
          />
          
          <div className="cart-item-info">
            <div className="cart-item-name">{item.name}</div>
            {item.selectedSpecs && (
              <div style={{ fontSize: '12px', color: '#999', marginBottom: '8px' }}>
                {Object.entries(item.selectedSpecs).map(([key, value]) => (
                  <span key={key}>{key}: {value} </span>
                ))}
              </div>
            )}
            <div className="cart-item-price">¥{item.price}</div>
            
            <div className="cart-item-controls">
              <div className="quantity-control">
                <button 
                  className="quantity-btn"
                  onClick={() => handleQuantityChange(item.cartId, item.quantity - 1)}
                >
                  -
                </button>
                <InputNumber
                  min={1}
                  value={item.quantity}
                  onChange={(value) => handleQuantityChange(item.cartId, value)}
                  className="quantity-input"
                  controls={false}
                />
                <button 
                  className="quantity-btn"
                  onClick={() => handleQuantityChange(item.cartId, item.quantity + 1)}
                >
                  +
                </button>
              </div>
              
              <Button
                type="text"
                icon={<DeleteOutlined />}
                onClick={() => handleRemoveItem(item.cartId)}
                style={{ marginLeft: '16px', color: '#ff4d4f' }}
              />
            </div>
          </div>
        </div>
              ))}
      </div>

      {/* 底部结算栏 */}
      <div className="cart-footer">
        <Checkbox
          checked={selectedItems.length === filteredItems.length && filteredItems.length > 0}
          onChange={(e) => handleSelectAll(e.target.checked)}
        >
          全选
        </Checkbox>
        
        <div className="cart-total">
          <div className="total-info">
            已选 {selectedItems.length} 件
          </div>
          <div className="total-amount">
            ¥{calculateTotal()}
          </div>
        </div>
        
        <Button
          type="primary"
          size="large"
          onClick={handleCheckout}
          disabled={selectedItems.length === 0}
          className="checkout-btn"
        >
          结算
        </Button>
      </div>
    </div>
  );
};

export default MobileCart; 